<template>
  <div class="register reset">
    <van-cell-group>
      <van-field v-model.trim="account" required clearable label="用户名" @blur="checkName" placeholder="请输入用户名"/>

      <van-field v-model.trim="passWord" type="password" label="密码" placeholder="请输入密码" @blur="checkPaw"
                 @input="dealTips" required/>
    </van-cell-group>
    <van-cell-group>
      <van-field placeholder="请输入右侧数字" v-model.trim="code" required label="验证码"/>
    </van-cell-group>
    <canvas id="myCanvas" width="70px" height="34px" @click="changTestCode"></canvas>
    <div class="tips">{{tips}}</div>
    <van-button type="info" @click="userRegister">免费注册</van-button>
  </div>
</template>

<script>
  import {fetch_login, fetch_register} from "../api";

  export default {
    name: "register",
    data() {
      return {
        account: '',
        passWord: '',
        code: '',
        tips: '',
        codes: ''
      }
    },
    mounted() {
      this.createCode()
    },
    methods: {
      checkName() {
        const params = {
          account: this.account,
          name: this.account
        }
        fetch_register(params).then((res) => {
          if (res.data.code === -1 && res.data.message) {
            this.tips = res.data.message
          }
        })
      },

      checkPaw() {
        if (this.passWord.length !== 0) {
          this.tips = ''
        } else {
          this.tips = '用户名和密码不能为空'
        }
      },

      dealTips() {
        this.tips = ''
      },

      userRegister() {
        if (this.codes.toLowerCase() != this.code.toLowerCase()) {
          this.tips = '验证码错误'
        } else {
          if (this.passWord.length !== 0) {
            const pa = {
              account: this.account,
              passWord: this.passWord,
              name: this.account
            }
            fetch_register(pa).then(() => {
              this.$store.state.showLr = false
              fetch_login(pa).then((res) => {
                if (res.data.code === 0) {
                  const token = res.data.data.token
                  sessionStorage.setItem('token', token)
                  sessionStorage.setItem('LoginFlag', this.$store.state.LoginFlag)
                  this.$store.commit('handleAccountName', this.account)
                  this.$store.commit('handleNickName', res.data.data.user.nick)
                  this.$store.state.LoginFlag = false
                  // this.$store.state.showLr = false
                  this.$router.push({path: '/home'})
                } else if (res.data.code === -1) {
                  window.alert('注册失败');
                }
              })
            })
          }
        }
      },
      createCode() {
        this.codes = ''
        const codeLength = 4;//验证码的长度，可变
        const canvas = document.getElementById('myCanvas');//获取画布
        const selectChar = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];//所有候选组成验证码的字符
        for (let i = 0; i < codeLength; i++) {
          let charIndex = Math.floor(Math.random() * 36);
          this.codes += selectChar[charIndex];
        }
        console.log(this.codes)
        if (canvas) {
          const ctx = canvas.getContext('2d');
          ctx.fillStyle = '#CCCCCC';
          ctx.textBaseline = "middle";
          ctx.textAlign = "center"
          ctx.fillRect(0, 0, 70, 34);
          ctx.font = "20px arial";
          // 创建渐变
          const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
          gradient.addColorStop("0", "magenta");
          gradient.addColorStop("0.5", "blue");
          gradient.addColorStop("1.0", "red");
          // 用渐变填色
          ctx.strokeStyle = gradient;
          ctx.strokeText(this.codes, 35, 20);//画布上添加验证码
        }
      },
      changTestCode() {
        this.createCode()
      }
    }
  }
</script>

<style scoped lang="less">
  .register {
    #myCanvas {
      position: absolute;
      top: 216px;
      right: 4%;
    }
  }
</style>
